<script setup>
import {ref, reactive, provide, inject, computed} from 'vue'
import router from '@/router'
import { ElMessageBox, ElBadge } from 'element-plus'
import LoginRegister from './components/App/LoginRegister.vue'
import TopMenu from './components/App/Menu.vue'
import axios from 'axios'
import { ElBreadcrumb, ElBreadcrumbItem } from 'element-plus'

const mitt=inject('mitt')
const mqtt=inject('mqtt')

//下拉菜单
const model_menu=ref(false)
function handleMenu(){
  model_menu.value=!model_menu.value
}
//面包屑导航
const routers=computed(()=>{
    return router.currentRoute.value.matched
})

//登录相关逻辑
const userinfo=ref()
provide("userinfo",userinfo)
var session_userinfo=sessionStorage.getItem('userinfo')
if(session_userinfo){
  userinfo.value=JSON.parse(session_userinfo)
}
mitt.on('userinfo',async ()=>{
  console.log('mitt:userinfo')
  try{
    var ret=await axios.get(`/api/user/${userinfo.value.id}`)
    userinfo.value=ret.data
    sessionStorage.setItem('userinfo',JSON.stringify(userinfo.value))
  }catch(err){
    console.error(`get: /api/user/${userinfo.value.id}出错：`,err)
  }
})

//刷新或关闭窗口前关闭mqtt连接
window.addEventListener('beforeunload',e=>{
  // e.preventDefault() //弹出框提醒是否离开页面
  e.returnValue=''
  if(mqtt?.connected) mqtt.end()
})

//登录前，点击右上角按钮，进入登录/注册页面
const show_login_register=ref(false)
function handleLoggin(){
  show_login_register.value=true
}

//登录后，点击右上角按钮，退出登录
function handleLogout(){
  ElMessageBox.confirm(
    '是否退出当前用户？',
    'Warning',
    {
      confirmButtonText:"确定",
      cancelButtonText:"取消",
      type:"warning"
    }
  ).then(()=>{
    if(mqtt?.connected){
      mqtt.unsubscribe(`/user/#`)
      mqtt.unsubscribe('/auditor')
      mqtt.unsubscribe('/reporter')
      mqtt.unsubscribe('/organization/#')
      mqtt.unsubscribe('/organization_admin/#')
    }
    //若当前页面为用户中心或管理入口，切换到主页
    if(router.currentRoute.value.path=='/usercenter'
    ||/^\/usercenter\/{1}.+$/.test(router.currentRoute.value.path)
    ||router.currentRoute.value.matched[0].name=='管理入口')
    {
      router.push('/')
    }
    sessionStorage.clear()
    userinfo.value=null
  }).catch(()=>{
    return
  })
}

//角标数据
const badge=reactive({
  //user
  notification_count:0,
  //auditor
  talent_audit_count:0,
})
provide('badge',badge)

//实时数据：通知数
async function refreshNotificationCount(){
  try{
    var ret=await axios.get(`/api/notification/${userinfo.value.id}/count`)
    badge.notification_count=ret.data
  }catch(err){
    console.error('mitt: notification_count', err)
  }
}
mitt.on('notification_count', refreshNotificationCount)
mitt.on('user_login', refreshNotificationCount)

async function refreshTalentAuditCount(){
    try{
        var ret=await axios.get('/api/talent_audit/count')
        badge.talent_audit_count=ret.data
    }catch(err){
        console.error('mitt: talent_audit_count', err)
    }
}
mitt.on('talent_audit_count',refreshTalentAuditCount)
mitt.on('auditor_login',refreshTalentAuditCount)

/* 
topics:对应不同权限
    /any                                    任何人（包括游客）
    /user/${user_id}                        所有用户
    /organization/${organization_id}        机构所有用户
    /organization_admin/${organization_id}  机构管理员
    /repoter                                媒体专员
    /auditor                                审核员
*/
mqtt.subscribe('/any',{qos:1})
mitt.on('login',()=>{
  if(userinfo.value){
    mqtt.subscribe(`/user/${userinfo.value.id}`,{qos:1})
    mitt.emit('user_login')
  }
  if(userinfo.value?.auditor){
    mqtt.subscribe('/auditor')
    mitt.emit('auditor_login')
  }
  if(userinfo.value?.reporter){
    mqtt.subscribe('/reporter')
    mitt.emit('reporter_login')
  }
  if(userinfo.value?.organization!=null){
    mqtt.subscribe(`/organization/${userinfo.value.organization.id}`)
    mitt.emit('organization_login')
  }
  if(userinfo.value?.organization_admin){
    mqtt.subscribe(`/organization_admin/${userinfo.value.organization.id}`)
    mitt.emit('organization_admin_login')
  }
})
mitt.emit('login')
</script>

<template>
  <LoginRegister v-model="show_login_register"/>
  <el-container>
    <el-header>
      <TopMenu v-model="model_menu"/>
      <div class="logo">
        <el-image src="/img/logo.png" fit="fill" @click="router.push('/')"></el-image>
      </div>
      <div class="topright">
        <div v-if=userinfo style="display:flex; justify-content: center; align-items: center; width:60px;">
          <el-badge :value="badge.notification_count==0?'':badge.notification_count">
            <router-link :to='{name:"通知"}'><el-image src="/img/icons/邮箱.png" style="width:28px; height:28px;"/></router-link>
          </el-badge>
        </div>
        <div class="topright-menu" @click=handleMenu>
          <div style="display:flex; align-items:center;">
              <el-image src="/img/icons/下拉菜单.png" style="width:16px; height:16px; margin-right:5px;"/>
              <span>菜单</span>
          </div>
        </div>
        <div v-if=!userinfo class="topright-unlogged" @click=handleLoggin>
          <span>登录/注册</span>
        </div>
        <div v-else class="topright-logged" @click=handleLogout>
          <span>
            {{ userinfo?userinfo.name:'' }}
            <br/>
            <svg t="1706249193586" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5964" width="22" height="22"><path d="M128 213.333333c0-46.933333 38.4-85.333333 85.333333-85.333333h341.333334v85.333333H213.333333v597.333334h341.333334v85.333333H213.333333c-46.933333 0-85.333333-38.4-85.333333-85.333333V213.333333z m604.842667 256L624.64 361.130667l60.330667-60.330667 211.2 211.2-211.2 211.2-60.330667-60.330667L732.842667 554.666667H451.84v-85.333334h281.002667z" fill="#fff" p-id="5965"></path></svg>
          </span>
        </div>
      </div>
    </el-header>
    <el-main>
      <div style="display:flex; align-items:center; padding:3px 0 3px 5px; margin-bottom:3px; background-color:var(--el-color-info-light-9);">
          <el-image style="width:12px; height:8px; margin-right:5px;" src="/img/breadcrumbs.png"/>
          <el-breadcrumb separator=">">
              <el-breadcrumb-item v-for="item in routers" :key="item.path" :to="{path:item?.path}">
                  {{ item?.name }}
              </el-breadcrumb-item>
          </el-breadcrumb>
      </div>
      <RouterView v-slot="{ Component }">
          <template v-if=" Component ">
              <Transition mode="out-in">
                    <component :is="Component"></component>
              </Transition>
          </template>
      </RouterView>
    </el-main>
    <el-footer>

    </el-footer>
  </el-container>
</template>

<style scoped>
.el-container{
  width:100vw;
}.el-container{
  max-width: 1024px;
}
.el-header{
  --el-header-padding:0;
  max-width: 1024px;
  display:flex;
  flex-direction:row;
  align-items:center;
  justify-content:space-between;
  background-color:rgba(255,255,255,0.85);
  height:auto;
  border-bottom-color: gray;
  border-bottom-width:2px;
  border-bottom-style:solid;
}
.logo{
  margin-left:10px;
  display:flex;
  align-items: center;
  cursor:pointer;
}
.logo:hover{
  background-color: var(--el-color-info-light-9);
}
.logo:active{
  background-color: var(--el-color-warning-light-9);
}
.topright{
  display:flex;
}
.topright-menu{
  width:90px;
  height:60px;
  cursor:pointer;
  color:white;
  display:flex;
  justify-content:center;
  align-items:center;
  background:linear-gradient(270deg,rgba(255, 106, 0, 0.6) 0%,#FF6A00 100%);
}span{
  font-weight:bolder;
}
.topright-menu:hover{
  background-color: green;
}
.topright-menu:active{
  background-color: red;
}
.topright-unlogged{
  width:90px;
  height:60px;
  cursor:pointer;
  color:white;
  display:flex;
  justify-content:center;
  align-items:center;
  background:linear-gradient(270deg,rgba(144, 147, 153, 0.4) 0%,#909399 100%);
}span{
  font-weight:bolder;
}
.topright-unlogged:hover{
  background-color: green;
}
.topright-unlogged:active{
  background-color: red;
}
.topright-logged{
  width:90px;
  height:60px;
  padding-top:10px;
  cursor:pointer;
  color:white;
  display:flex;
  justify-content:center;
  align-items:center;
  background:linear-gradient(270deg,rgb(64, 158, 255, 0.6) 0%,#409EFF 100%);
}span{
  font-weight:bolder;
  text-align: center;
  font-size: small;
}
.topright-logged:hover{
  background-color: green;
}
.topright-logged:active{
  background-color: red;
}
.el-main{
  --el-main-padding:0;
}
</style>